<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8" />
  <title>路径可视化 - 输入交互版（增强）</title>
  <script src="https://unpkg.com/cytoscape@3.26.0/dist/cytoscape.min.js"></script>
  <style>
    #cy {
      width: 100%;
      height: 600px;
      border: 1px solid #ccc;
      box-sizing: border-box;
      margin-top: 10px;
    }
    label {
      display: inline-block;
      width: 100px;
      margin-right: 10px;
    }
    input {
      width: 200px;
      margin-bottom: 10px;
    }
    button {
      padding: 6px 12px;
      font-size: 16px;
      margin-left: 5px;
    }
    .occupied-node {
      margin-bottom: 5px;
    }
  </style>
</head>
<body>
<h2>路径可视化 - 输入交互（增强版）</h2>

<div>
  <label for="start">起点:</label>
  <input type="text" id="start" value="A1" /><br />

  <label for="end">终点:</label>
  <input type="text" id="end" value="B10" /><br />

  <label for="currentNode">当前点:</label>
  <input type="text" id="currentNode" placeholder="可选" readonly /><br />

  <label for="agvName">Agv名称:</label>
  <input type="text" id="agvName" placeholder="可选" /><br />

  <button id="showPathBtn">显示路径</button>
</div>

<hr />

<div>
  <label for="occupyInput">占用节点:</label>
  <input type="text" id="occupyInput" placeholder="A1,A2" />
  <button onclick="occupyNodes()">设置占用</button><br />

  <label for="releaseInput">释放节点:</label>
  <input type="text" id="releaseInput" placeholder="A1,A2" />
  <button onclick="releaseNodes()">释放占用</button>
</div>

<hr />

<div>
  <h3>当前已占用节点：</h3>
  <div id="occupiedList"></div>
  <button onclick="clearAllOccupied()">清空所有占用节点</button>
</div>

<div id="cy"></div>

<script>
  let cy = null;
  let lastKnownCurrentNode = null;

  async function loadGraph(start, end) {
    const params = new URLSearchParams();
    params.append("start", start);
    params.append("end", end);

    const response = await fetch(`/graph/path/visual?` + params.toString());
    const data = await response.json();

    if (cy) cy.destroy();

    cy = cytoscape({
      container: document.getElementById('cy'),
      elements: data.elements,
      style: [
        {
          selector: 'node',
          style: {
            'label': 'data(label)',
            'text-valign': 'center',
            'color': '#000',
            'background-color': '#007bff',
            'width': 40,
            'height': 40,
            'font-size': 14
          }
        },
        {
          selector: 'node[current]',
          style: {
            'background-color': '#ff5722',
            'border-color': '#000',
            'border-width': 3
          }
        },
        {
          selector: 'node[occupied]',
          style: {
            'background-color': '#6c757d',
            'border-color': '#333',
            'border-width': 2
          }
        },
        {
          selector: 'edge',
          style: {
            'width': 4,
            'line-color': '#999',
            'target-arrow-color': '#999',
            'target-arrow-shape': 'triangle',
            'curve-style': 'bezier'
          }
        },
        {
          selector: 'edge[bidirectional = "true"]',
          style: {
            'source-arrow-shape': 'triangle',
            'source-arrow-color': '#999'
          }
        }
      ],
      layout: {
        name: 'grid',
        rows: 1,
        cols: data.path.length,
        padding: 10
      }
    });

    // 点击节点事件
    cy.on('tap', 'node', function(evt) {
      const data = evt.target.data();
      const message = `
        节点: ${data.label}
        当前点: ${data.current ? '是' : '否'}
        占用: ${data.occupied ? '是' : '否'}
      `;
      alert(message.trim());
    });

    // 点击边事件
    cy.on('tap', 'edge', function(evt) {
      const data = evt.target.data();
      const message = `
        起点: ${data.source}
        终点: ${data.target}
        双向: ${data.bidirectional === 'true' ? '是' : '否'}
      `;
      alert(message.trim());
    });
  }

  async function fetchCurrentNodeAndUpdate() {
    try {
      const agvName = document.getElementById('agvName').value.trim();
      const params = new URLSearchParams();
      if (agvName) params.append('agvName', agvName);

      const res = await fetch('/graph/getCurrentNode', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: params.toString()
      });
      if (!res.ok) return;
      const nodes = await res.json();

      if (nodes.length > 0) {
        const displayNodes = nodes.join(', ');
        if (displayNodes !== lastKnownCurrentNode) {
          document.getElementById('currentNode').value = displayNodes;
          lastKnownCurrentNode = displayNodes;
        }
      } else {
        document.getElementById('currentNode').value = '';
        lastKnownCurrentNode = '';
      }
    } catch (e) {
      console.error('获取当前节点失败', e);
    }
  }

  setInterval(fetchCurrentNodeAndUpdate, 3000);

  async function occupyNodes() {
    const nodes = document.getElementById('occupyInput').value.trim().split(',').filter(Boolean);
    if (nodes.length === 0) {
      alert('请输入要占用的节点');
      return;
    }

    const res = await fetch('/graph/occupy', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(nodes)
    });

    if (res.ok) {
      alert('占用节点成功: ' + nodes.join(', '));
      loadOccupiedNodes();
    } else {
      alert('占用失败');
    }
  }

  async function releaseNodes() {
    const nodes = document.getElementById('releaseInput').value.trim().split(',').filter(Boolean);
    if (nodes.length === 0) {
      alert('请输入要释放的节点');
      return;
    }

    const res = await fetch('/graph/release', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(nodes)
    });

    if (res.ok) {
      alert('释放成功: ' + nodes.join(', '));
      loadOccupiedNodes();
    } else {
      alert('释放失败');
    }
  }

  async function loadOccupiedNodes() {
    const res = await fetch('/graph/listOccupiedNode', { method: 'POST' });
    const nodes = await res.json();
    const container = document.getElementById('occupiedList');
    container.innerHTML = '';

    if (nodes.length === 0) {
      container.innerHTML = '<i>暂无占用节点</i>';
      return;
    }

    nodes.forEach(node => {
      const div = document.createElement('div');
      div.className = 'occupied-node';

      const label = document.createElement('span');
      label.textContent = node;
      label.style.marginRight = '10px';

      const btn = document.createElement('button');
      btn.textContent = '释放';
      btn.onclick = async () => {
        const res = await fetch('/graph/release', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify([node])
        });
        if (res.ok) {
          alert(`已释放节点: ${node}`);
          loadOccupiedNodes();
        }
      };

      div.appendChild(label);
      div.appendChild(btn);
      container.appendChild(div);
    });
  }

  async function clearAllOccupied() {
    const confirmClear = confirm('确定要清空所有占用节点？');
    if (!confirmClear) return;

    const res = await fetch('/graph/clear', { method: 'POST' });
    if (res.ok) {
      alert('已清空占用节点');
      loadOccupiedNodes();
    } else {
      alert('清空失败');
    }
  }

  document.getElementById('showPathBtn').addEventListener('click', () => {
    const start = document.getElementById('start').value.trim();
    const end = document.getElementById('end').value.trim();

    if (!start || !end) {
      alert('请填写起点和终点');
      return;
    }

    loadGraph(start, end);
  });

  window.onload = () => {
    fetchCurrentNodeAndUpdate();
    loadOccupiedNodes();
  };
</script>
</body>
</html>
